Page({
  data: {
    title: '',
    content: '',
    tempImage: '',
    canSubmit: false,
    backendUrl: 'http://127.0.0.1:88/api/user/'
  },

  // 处理标题输入
  handleTitleInput(e) {
    this.setData({
      title: e.detail.value
    }, this.checkCanSubmit);
  },

  // 处理内容输入
  handleContentInput(e) {
    this.setData({
      content: e.detail.value
    }, this.checkCanSubmit);
  },

  // 检查是否可以提交
  checkCanSubmit() {
    const { title, content } = this.data;
    this.setData({
      canSubmit: title.trim() && content.trim()
    });
  },

  // 选择图片
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({
          'tempImage': tempFilePath
        });
      }
    });
  },

  // 移除图片
  removeImage() {
    this.setData({
      tempImage: ''
    });
  },

  // 提交帖子
  submitPost() {
    if (!this.data.canSubmit) return;

    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '发布中...' });

    // 直接上传图片和帖子内容
    wx.uploadFile({
      url: this.data.backendUrl + 'post.php',
      filePath: this.data.tempImage,
      name: 'image',
      formData: {
        action: 'create',
        user_id: userInfo.id,
        title: this.data.title.trim(),
        content: this.data.content.trim()
      },
      header: {
        "Content-Type": "multipart/form-data"
      },
      success: (res) => {
        wx.hideLoading();
        try {
          const data = JSON.parse(res.data);
          if (data.status === 'success') {
            wx.showToast({
              title: '发布成功',
              icon: 'success'
            });
            setTimeout(() => {
              // 返回并刷新上一页
              const pages = getCurrentPages();
              const prevPage = pages[pages.length - 2];
              if (prevPage) {
                prevPage.setData({
                  page: 1,
                  posts: []
                }, () => {
                  prevPage.loadPosts();
                  wx.navigateBack();
                });
              } else {
                wx.navigateBack();
              }
            }, 1500);
          } else {
            wx.showToast({
              title: data.message || '发布失败',
              icon: 'none'
            });
          }
        } catch (e) {
          wx.showToast({
            title: '服务器返回数据格式错误',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: '发布失败，请重试',
          icon: 'none'
        });
      }
    });
  }
}) 